package main

import (
	"fmt"
	"sync"
	"sync/atomic"
)

func main() {
	{
		num := 0
		wait1 := sync.WaitGroup{}
		wait1.Add(10000)
		for i := 0; i < 10000; i++ {
			go func() {
				num += 1
				wait1.Done()
			}()
		}
		wait1.Wait()
		fmt.Println(num)
	}

	{
		wait1 := sync.WaitGroup{}
		// atomic
		var num int64
		wait1.Add(10000)
		for i := 0; i < 10000; i++ {
			go func() {
				atomic.AddInt64(&num, 1)
				wait1.Done()
			}()
		}

		wait1.Wait()
		tmpNum := atomic.LoadInt64(&num)
		fmt.Println(tmpNum, num, &tmpNum, &num)
	}

	{
		// 先比较变量的值是否等于给定旧值，等于旧值的情况下才赋予新值，最后返回新值是否设置成功。
		var sum uint32 = 100
		var wg sync.WaitGroup
		for i := uint32(0); i < 100; i++ {
			wg.Add(1)
			go func(t uint32) {
				defer wg.Done()
				atomic.CompareAndSwapUint32(&sum, 100, sum+1)
			}(i)
		}
		wg.Wait()
		fmt.Println(sum)
	}

}
